package com.hybrid.webview;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import android.os.Build;
import android.os.Handler;
import android.os.Message;
import com.hybrid.utils.TaoLog;

/**
 * 在此写用途
 *
 * @author: zhiwei
 * @date: 2017-10-09 22:06
 * @version: 9.1.0
 */
public class WVTweakWebCoreHandler {
    static Handler sProxyHandler = null;

    public static void tryTweakWebCoreHandler() {
        // 4.0.3/4.0.4 rom Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1
        if (Build.VERSION.SDK_INT == 15 && !"SAMSUNG".equalsIgnoreCase(Build.BRAND)) {
            if (TaoLog.getLogStatus()) {
                TaoLog.w("TweakWebCoreHandler", "BRAND: " + Build.BRAND);
            }
            tweakWebCoreHandler();
        }
    }

    private static void tweakWebCoreHandler() {
        if (sProxyHandler != null)
            return;
        try {
            Field f = Class.forName("android.webkit.WebViewCore").getDeclaredField("sWebCoreHandler");
            f.setAccessible(true);
            Object h = f.get(null);
            Method m = Handler.class.getDeclaredMethod("getIMessenger", (Class<?>[]) null);
            m.setAccessible(true);
            Object mMessenger = m.invoke(h, (Object[]) null);
            sProxyHandler = new WebCoreProxyHandler((Handler) h);
            if (mMessenger != null) {
                Field f1 = Handler.class.getDeclaredField("mMessenger");
                f1.setAccessible(true);
                f1.set(sProxyHandler, mMessenger);
            }
            f.set(null, sProxyHandler);
            if (TaoLog.getLogStatus()) {
                TaoLog.d("TweakWebCoreHandler", "sWebCoreHandler: " + h);
            }
        } catch (Throwable e) {
            TaoLog.e("TweakWebCoreHandler", "tweakWebCoreHandler exception: " + e);
        }
        if (sProxyHandler == null)
            sProxyHandler = new Handler();
    }

    static class WebCoreProxyHandler extends Handler {
        final Handler handler;

        public WebCoreProxyHandler(Handler handler) {
            super(handler.getLooper());
            this.handler = handler;
        }

        @Override
        public void handleMessage(Message msg) {
            try {
                if (TaoLog.getLogStatus()) {
                    TaoLog.d("WebCoreProxyHandler", "handle message: " + msg.what);
                }
                handler.handleMessage(msg);
            } catch (Throwable e) {
                TaoLog.e("WebCoreProxyHandler", "handleMessage exception: " + e);
            }
        }
    }
}
